import React, { useState, useEffect } from 'react';
import { Box } from '@mui/material';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { DateSelectArg, EventClickArg } from '@fullcalendar/core';
import { format, isBefore } from 'date-fns';
import { Meeting } from './types';
import { MeetingForm } from './components/MeetingForm';
import { StyledCalendarWrapper } from './components/Calendar.styles';

const MeetingsPage: React.FC = () => {
  const [meetings, setMeetings] = useState<Meeting[]>(() => {
    const storedMeetings = localStorage.getItem('meetings');
    return storedMeetings ? JSON.parse(storedMeetings) : [];
  });
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedMeeting, setSelectedMeeting] = useState<Meeting | null>(null);
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);

  useEffect(() => {
    localStorage.setItem('meetings', JSON.stringify(meetings));
  }, [meetings]);

  const checkTimeOverlap = (start: Date, end: Date, currentMeetingId?: string): boolean => {
    return meetings.some(meeting => {
      if (meeting.id === currentMeetingId) return false;
      const meetingStart = new Date(meeting.start);
      const meetingEnd = new Date(meeting.end);

      if (format(meetingStart, 'yyyy-MM-dd') !== format(start, 'yyyy-MM-dd')) {
        return false;
      }

      return (start > meetingStart && start < meetingEnd) ||
             (end > meetingStart && end < meetingEnd) ||
             (start <= meetingStart && end >= meetingEnd);
    });
  };

  const handleDateSelect = (selectInfo: DateSelectArg) => {
    const date = new Date(selectInfo.start);
    
    if (isBefore(date, new Date())) {
      return;
    }
    
    setSelectedDate(date);
    setSelectedMeeting(null);
    setIsDialogOpen(true);
  };

  const handleEventClick = (clickInfo: EventClickArg) => {
    const event = meetings.find(m => m.id === clickInfo.event.id);
    if (event) {
      setSelectedDate(new Date(event.start));
      setSelectedMeeting(event);
      setIsDialogOpen(true);
    }
  };

  const handleSaveMeeting = (meeting: Meeting) => {
    if (checkTimeOverlap(new Date(meeting.start), new Date(meeting.end), meeting.id)) {
      return;
    }

    setMeetings(prev => {
      const filtered = prev.filter(m => m.id !== meeting.id);
      return [...filtered, meeting];
    });
    setIsDialogOpen(false);
  };

  const handleDeleteMeeting = () => {
    if (selectedMeeting) {
      setMeetings(prev => prev.filter(meeting => meeting.id !== selectedMeeting.id));
      setIsDialogOpen(false);
    }
  };

  return (
    <StyledCalendarWrapper sx={{ p: 3, height: 'calc(100vh - 100px)' }}>
      <FullCalendar
        plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
        headerToolbar={{
          left: 'prev,next today',
          center: 'title',
          right: ''
        }}
        initialView="dayGridMonth"
        editable={true}
        selectable={true}
        selectMirror={true}
        dayMaxEvents={false}
        weekends={true}
        events={meetings.map(meeting => ({
          ...meeting,
          classNames: ['meeting-event']
        }))}
        select={handleDateSelect}
        eventClick={handleEventClick}
        height="100%"
        allDaySlot={false}
        dayCellClassNames={(arg) => {
          return isBefore(arg.date, new Date()) ? ['past-date'] : [];
        }}
        selectConstraint={{
          start: new Date().toISOString(),
          end: '2100-01-01'
        }}
        eventContent={(eventInfo) => (
          <Box sx={{
            p: 0.5,
            fontSize: '0.9em',
            overflow: 'hidden',
            whiteSpace: 'normal',
            wordWrap: 'break-word'
          }}>
            {format(eventInfo.event.start as Date, 'HH:mm')} - {format(eventInfo.event.end as Date, 'HH:mm')} {eventInfo.event.title}
          </Box>
        )}
        firstDay={1}
      />

      <MeetingForm
        isOpen={isDialogOpen}
        onClose={() => setIsDialogOpen(false)}
        onSave={handleSaveMeeting}
        onDelete={selectedMeeting ? handleDeleteMeeting : undefined}
        meeting={selectedMeeting}
        selectedDate={selectedDate}
      />
    </StyledCalendarWrapper>
  );
};

export default MeetingsPage;